package com.ilxqx.framework.system.controller;

import com.ilxqx.framework.security.constant.SecurityConstants;
import com.ilxqx.framework.security.util.AuthUtils;
import com.ilxqx.framework.system.controller.base.AbstractFrameworkController;
import com.ilxqx.framework.system.entity.SysPermission;
import com.ilxqx.framework.system.entity.SysRole;
import com.ilxqx.framework.system.exception.UpdateDeniedException;
import com.ilxqx.framework.system.form.search.SysRoleSearchForm;
import com.ilxqx.framework.system.form.update.SysRoleUpdateForm;
import com.ilxqx.framework.system.service.SysPermissionService;
import com.ilxqx.framework.system.service.SysRoleService;
import com.ilxqx.framework.util.ResultUtils;
import com.ilxqx.framework.vo.ResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 系统角色控制器
 * @author venus
 */
@Api("系统角色控制器")
@RestController
@RequestMapping("/auth/sys-role")
@Slf4j
public class SysRoleController extends AbstractFrameworkController<SysRole, Long, SysRoleSearchForm, SysRoleUpdateForm> {

	private final SysRoleService sysRoleService;
	private final SysPermissionService sysPermissionService;
	private final JdbcTemplate jdbcTemplate;

	@Autowired
	public SysRoleController(SysRoleService sysRoleService, SysPermissionService sysPermissionService, JdbcTemplate jdbcTemplate) {
		super(sysRoleService);
		this.sysRoleService = sysRoleService;
		this.sysPermissionService = sysPermissionService;
		this.jdbcTemplate = jdbcTemplate;
	}

	/**
	 * 获取系统中的所有角色
	 * @return 系统角色
	 */
	@ApiOperation("获取系统中的所有角色")
	@GetMapping("/roles")
	public ResultVO getRoles() {
		return ResultUtils.success("成功", this.sysRoleService.getList(Sort.by(Sort.Order.desc("createTime"))));
	}

	/**
	 * 获取角色权限
	 * @param roleId 角色ID
	 * @return 结果对象
	 */
	@ApiOperation("获取角色权限")
	@GetMapping("/permissions")
	public ResultVO getUserRoles(@RequestParam Long roleId) {
		Optional<SysRole> sysRoleOptional = this.sysRoleService.get(roleId);
		if (sysRoleOptional.isEmpty()) {
			return ResultUtils.failure("角色不存在");
		}
		Set<SysPermission> rolePermissions = sysRoleOptional.get().getRolePermissions();
		return ResultUtils.success("成功", rolePermissions.stream().map(SysPermission::getPermissionId).collect(Collectors.toList()));
	}

	@Override
	public void beforeModify(SysRole entity, SysRoleUpdateForm form) {
		// 如果是超级管理员用户，则只能由超级管理员来修改
		if (Objects.equals(entity.getRoleId(), SecurityConstants.SUPER_ADMIN_ROLE_ID) &&
				!Objects.equals(AuthUtils.getLoggedUserId(), SecurityConstants.SUPER_ADMIN_USER_ID)) {
			throw new UpdateDeniedException("您没有权限修改超级管理员角色的信息");
		}
	}

	/**
	 * 分配权限
	 * @param roleId 角色ID
	 * @param permissionIds 权限ID字符串（用英文逗号分隔）
	 * @return 结果对象
	 */
	@ApiOperation("分配角色")
	@PutMapping("/allocate")
	public ResultVO allocate(@RequestParam Long roleId, @RequestParam String permissionIds) {
		if (Objects.equals(roleId, SecurityConstants.SUPER_ADMIN_ROLE_ID)) {
			return ResultUtils.failure("不能为超级管理员角色分配权限");
		}
		Optional<SysRole> sysRoleOptional = this.sysRoleService.get(roleId);
		if (sysRoleOptional.isEmpty()) {
			return ResultUtils.failure("角色不存在");
		}
		SysRole sysRole = sysRoleOptional.get();
		Set<SysPermission> rolePermissions = sysRole.getRolePermissions();
		// 获取选中的权限
		List<SysPermission> allPermissions = this.sysPermissionService.getList(Arrays.stream(StringUtils.split(permissionIds, ",")).map(Long::parseLong).collect(Collectors.toList()));

		// 找出需要删除的
		Set<SysPermission> deletePermissions = rolePermissions.stream()
				.filter(sysPermission -> !allPermissions.contains(sysPermission))
				.collect(Collectors.toSet());
		rolePermissions.removeAll(deletePermissions);
		rolePermissions.addAll(allPermissions);
		this.sysRoleService.modify(sysRole);
		return ResultUtils.success("权限分配成功");
	}

	@Override
	public void beforeDelete(SysRole entity) {
		if (Objects.equals(entity.getRoleId(), SecurityConstants.SUPER_ADMIN_ROLE_ID)) {
			throw new UpdateDeniedException("不能删除超级管理员角色");
		}
	}

	/**
	 * 在实体删除之后的处理
	 *
	 * @param entity 删除完的实体对象
	 * @return 返回数据
	 */
	@Override
	public Object afterDelete(SysRole entity) {
		this.jdbcTemplate.update("delete from sys_user_role where role_id = ?", entity.getRoleId());
		return null;
	}

}
